package com.zjitc.token;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import sun.awt.geom.AreaOp.EOWindOp;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/2 13:47
 * @description:
 *
 *  缓存
 *  将token存入到对应在一个map中，然后这个缓存会没500ms进行一次扫描，如果发现有存储的token内容，时间超过了
 *  1s中，则需要删除这个数据
 *  1. 存入token的时候，需要附加内容(时间)
 *      value:
 *      1. token
 *      2. 时间
 *  2.  key: username
 *
 */
public class Cache {

   private Map<String, Token> tokens = new ConcurrentHashMap<>();


  public void add(String username, String uuid) {
    tokens.put(username, new Token(uuid, LocalDateTime.now()));
  }

  public Token get(String username) {
    return tokens.get(username);    // get remove
  }

  public Set<Entry<String, Token>> getAllTokens() {
    return tokens.entrySet();
  }

  /**
   * 如何使用多线程，在后台一直对Cache进行扫描
   */
  public static void main(String[] args) {
    Cache cache = new Cache();

    cache.add("a", "a");
    cache.add("b", "b");
    cache.add("c", "c");

    //ExecutorService executor = Executors.newSingleThreadExecutor();
    ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
    System.out.println("当前时间: " + LocalDateTime.now());
    service.scheduleAtFixedRate(() -> {
      System.out.println("第一次运行的时间" + LocalDateTime.now());
      while (true) {


        // 检查在Cache中，是否有数据过期，如果亦，则将其打印出来)
        Set<Entry<String, Token>> sets = cache.getAllTokens();

        // 需要计算时间间隔
        for (Entry<String, Token> entry : sets) {
          String key = entry.getKey();
          Token token = entry.getValue();

          LocalDateTime creatTime = token.getCreateTime();
          LocalDateTime nowTime = LocalDateTime.now();

          // 如何计算时间间
          Duration between = Duration.between(creatTime, nowTime);
          if (between.abs().toMillis() > 5000) {
            System.out.println(token.getUuid());
          }
        }
      }
    }, 1000, 1000, TimeUnit.MILLISECONDS);

    Scanner s = new Scanner(System.in);
    s.next();
  }

  @Test
  public void druing() {
    LocalDateTime t1 = LocalDateTime.now();
    try {
      Thread.sleep(1020);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    LocalDateTime t2 = LocalDateTime.now();

    System.out.println(t1);
    System.out.println(t2);

    // 怎么对t1和t2求时间间隔
    Duration between = Duration.between(t1, t2);
    System.out.println(between.abs().toMillis());
  }
}
